import {
  Controller,
  Get,
  Post,
  Delete,
  Body,
  Query,
  Param,
  UseGuards,
  Request,
  ParseIntPipe,
  BadRequestException,
} from '@nestjs/common';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { InteractionService } from './interaction.service';
import {
  AddFavoriteDto,
  GetFavoritesDto,
  AddReadingHistoryDto,
  GetReadingHistoryDto,
  CreateCommentDto,
  GetCommentsDto,
  UpdateCommentDto,
  CreateBookshelfDto,
  UpdateBookshelfDto,
  GetBookshelvesDto,
  MoveToFavoritesDto,
} from './dto/interaction.dto';

@Controller('novels/interaction')
export class InteractionController {
  constructor(private readonly interactionService: InteractionService) {}

  /**
   * 添加小说到收藏
   */
  @UseGuards(JwtAuthGuard)
  @Post('favorites')
  async addFavorite(@Request() req, @Body() addFavoriteDto: AddFavoriteDto) {
    const userId = req.user.userId;
    return this.interactionService.addToFavorite(
      userId,
      addFavoriteDto.novelId,
      addFavoriteDto.bookshelfId,
    );
  }

  /**
   * 取消收藏小说
   */
  @UseGuards(JwtAuthGuard)
  @Delete('favorites/:novelId')
  async removeFavorite(
    @Request() req,
    @Param('novelId', ParseIntPipe) novelId: number,
  ) {
    const userId = req.user.userId;
    return this.interactionService.removeFromFavorite(userId, novelId);
  }

  /**
   * 检查是否已收藏
   */
  @UseGuards(JwtAuthGuard)
  @Get('favorites/check/:novelId')
  async checkFavorite(
    @Request() req,
    @Param('novelId', ParseIntPipe) novelId: number,
  ) {
    const userId = req.user.userId;
    const isFavorited = await this.interactionService.checkFavorite(
      userId,
      novelId,
    );
    return { isFavorited };
  }

  /**
   * 获取用户收藏列表
   */
  @UseGuards(JwtAuthGuard)
  @Get('favorites')
  async getFavorites(
    @Request() req,
    @Query() getFavoritesDto: GetFavoritesDto,
  ) {
    const userId = req.user.userId;
    return this.interactionService.getUserFavorites(userId, getFavoritesDto);
  }

  /**
   * 添加阅读历史
   */
  @UseGuards(JwtAuthGuard)
  @Post('reading-history')
  async addReadingHistory(
    @Request() req,
    @Body() addReadingHistoryDto: AddReadingHistoryDto,
  ) {
    const userId = req.user.userId;
    return this.interactionService.addReadingHistory(userId, {
      novelId: addReadingHistoryDto.novelId,
      chapterId: addReadingHistoryDto.chapterId,
      readProgress: addReadingHistoryDto.readProgress,
    });
  }

  /**
   * 获取阅读历史
   */
  @UseGuards(JwtAuthGuard)
  @Get('reading-history')
  async getReadingHistory(
    @Request() req,
    @Query() getReadingHistoryDto: GetReadingHistoryDto,
  ) {
    const userId = req.user.userId;
    return this.interactionService.getUserReadingHistory(
      userId,
      getReadingHistoryDto,
    );
  }

  /**
   * 获取小说阅读进度
   */
  @UseGuards(JwtAuthGuard)
  @Get('reading-progress/:novelId')
  async getReadingProgress(
    @Request() req,
    @Param('novelId', ParseIntPipe) novelId: number,
  ) {
    const userId = req.user.userId;
    const progress = await this.interactionService.getReadingProgress(
      userId,
      novelId,
    );
    return { progress };
  }

  /**
   * 创建评论
   */
  @UseGuards(JwtAuthGuard)
  @Post('comments')
  async createComment(
    @Request() req,
    @Body() createCommentDto: CreateCommentDto,
  ) {
    const userId = req.user.userId;
    return this.interactionService.createComment(userId, {
      novelId: createCommentDto.novelId,
      chapterId: createCommentDto.chapterId,
      content: createCommentDto.content,
      parentId: createCommentDto.parentId,
    });
  }

  /**
   * 获取评论列表
   */
  @Get('comments')
  async getComments(@Query() getCommentsDto: GetCommentsDto) {
    return this.interactionService.getComments(getCommentsDto);
  }

  /**
   * 获取评论详情
   */
  @Get('comments/:commentId')
  async getCommentDetail(@Param('commentId', ParseIntPipe) commentId: number) {
    return this.interactionService.getCommentDetail(commentId);
  }

  /**
   * 更新评论
   */
  @UseGuards(JwtAuthGuard)
  @Post('comments/:commentId/update')
  async updateComment(
    @Request() req,
    @Param('commentId', ParseIntPipe) commentId: number,
    @Body() updateCommentDto: UpdateCommentDto,
  ) {
    const userId = req.user.userId;
    return this.interactionService.updateComment(
      userId,
      commentId,
      updateCommentDto.content,
    );
  }

  /**
   * 删除评论
   */
  @UseGuards(JwtAuthGuard)
  @Delete('comments/:commentId')
  async deleteComment(
    @Request() req,
    @Param('commentId', ParseIntPipe) commentId: number,
  ) {
    const userId = req.user.userId;
    return this.interactionService.deleteComment(userId, commentId);
  }

  /**
   * 点赞评论
   */
  @UseGuards(JwtAuthGuard)
  @Post('comments/:commentId/like')
  async likeComment(
    @Request() req,
    @Param('commentId', ParseIntPipe) commentId: number,
  ) {
    const userId = req.user.userId;
    return this.interactionService.likeComment(commentId);
  }

  /**
   * 取消点赞评论
   */
  @UseGuards(JwtAuthGuard)
  @Delete('comments/:commentId/like')
  async unlikeComment(
    @Request() req,
    @Param('commentId', ParseIntPipe) commentId: number,
  ) {
    const userId = req.user.userId;
    return this.interactionService.unlikeComment(commentId);
  }

  /**
   * 获取用户的评论列表
   */
  @UseGuards(JwtAuthGuard)
  @Get('user-comments')
  async getUserComments(
    @Request() req,
    @Query() query: { page?: number; limit?: number },
  ) {
    const userId = req.user.userId;
    return this.interactionService.getUserComments(userId, query);
  }

  /**
   * 批量操作：批量删除收藏
   */
  @UseGuards(JwtAuthGuard)
  @Delete('favorites/batch')
  async batchRemoveFavorites(
    @Request() req,
    @Body() body: { novelIds: number[] },
  ) {
    const userId = req.user.userId;
    if (!body.novelIds || body.novelIds.length === 0) {
      throw new BadRequestException('请提供要删除的小说ID列表');
    }

    const results = await Promise.all(
      body.novelIds.map((novelId) =>
        this.interactionService.removeFromFavorite(userId, novelId),
      ),
    );

    return {
      success: results.filter((r) => r.success).length,
      failed: results.filter((r) => !r.success).length,
    };
  }

  /**
   * 清空阅读历史
   */
  @UseGuards(JwtAuthGuard)
  @Delete('reading-history/clear')
  async clearReadingHistory(@Request() req) {
    const userId = req.user.userId;
    return this.interactionService.clearReadingHistory(userId);
  }

  // ==================== 书架管理API ====================

  /**
   * 创建书架
   */
  @UseGuards(JwtAuthGuard)
  @Post('bookshelves')
  async createBookshelf(@Request() req, @Body() createBookshelfDto: CreateBookshelfDto) {
    const userId = req.user.userId;
    return this.interactionService.createBookshelf(userId, createBookshelfDto);
  }

  /**
   * 获取用户书架列表
   */
  @UseGuards(JwtAuthGuard)
  @Get('bookshelves')
  async getBookshelves(@Request() req, @Query() getBookshelvesDto: GetBookshelvesDto) {
    const userId = req.user.userId;
    return this.interactionService.getUserBookshelves(userId, getBookshelvesDto);
  }

  /**
   * 更新书架
   */
  @UseGuards(JwtAuthGuard)
  @Post('bookshelves/:bookshelfId/update')
  async updateBookshelf(
    @Request() req,
    @Param('bookshelfId', ParseIntPipe) bookshelfId: number,
    @Body() updateBookshelfDto: UpdateBookshelfDto,
  ) {
    const userId = req.user.userId;
    return this.interactionService.updateBookshelf(userId, bookshelfId, updateBookshelfDto);
  }

  /**
   * 删除书架
   */
  @UseGuards(JwtAuthGuard)
  @Delete('bookshelves/:bookshelfId')
  async deleteBookshelf(
    @Request() req,
    @Param('bookshelfId', ParseIntPipe) bookshelfId: number,
  ) {
    const userId = req.user.userId;
    return this.interactionService.deleteBookshelf(userId, bookshelfId);
  }

  /**
   * 批量移动收藏到指定书架
   */
  @UseGuards(JwtAuthGuard)
  @Post('bookshelves/move-favorites')
  async moveFavoritesToBookshelf(
    @Request() req,
    @Body() moveToFavoritesDto: MoveToFavoritesDto,
  ) {
    const userId = req.user.userId;
    return this.interactionService.moveFavoritesToBookshelf(userId, moveToFavoritesDto);
  }
}
